package org.ns.longhttp.selector.datamapper;

import org.ns.longhttp.selector.datamapper.responseid.DataResponseIdService;

import java.util.*;

/**
 * 数据映射的实体
 */
public class DefaultDataMappingEntry extends DataMappingEntry {

    /**
     * 数据队列存储DataResponseEntry对象
     */
    private final TreeMap<Long, DataResponseEntryWrapper> dataQueue = new TreeMap<>();


    /**
     * 数据映射实体
     * @param key
     * @param responseIdService
     */
    public DefaultDataMappingEntry(String key, DataResponseIdService responseIdService) {
        super(key, responseIdService);
    }

    /**
     * 添加数据应答实体
     * @param dataResponseEntry
     * @param second  超时时间 "秒"
     */
    public void put(long id, DataResponseEntry dataResponseEntry, int second) {
        synchronized (dataQueue) {
            // 设置失效时间
            long invalidTime = System.currentTimeMillis() + second * 1000;
            DataResponseEntryWrapper dataResponseEntryWrapper = new DataResponseEntryWrapper(dataResponseEntry, invalidTime);
            dataQueue.put(id, dataResponseEntryWrapper);
        }
    }

    /**
     * 清理失效的数据
     */
    public void clearInvalid() {
        synchronized (dataQueue) {
            Iterator<Map.Entry<Long, DataResponseEntryWrapper>> iterator = dataQueue.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, DataResponseEntryWrapper> next = iterator.next();
                DataResponseEntryWrapper value = next.getValue();
                if (value.isInvalid()) {
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 获得下一批数据、获得的数据的ID一定比传入的ID大
     * @param id
     * @return
     */
    public List<DataResponseEntry> getDataResponseEntrys(long id) {
        List<DataResponseEntry> entries = new ArrayList<>();
        if (!hasNew(id)) { // 没有新的数据则返回空集合
            return entries;
        }
        synchronized (dataQueue) {
            SortedMap<Long, DataResponseEntryWrapper> sortedMap = dataQueue.tailMap(id, false);
            Iterator<Map.Entry<Long, DataResponseEntryWrapper>> iterator = sortedMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, DataResponseEntryWrapper> next = iterator.next();
                DataResponseEntryWrapper value = next.getValue();
                if (value.isInvalid()) {
                    iterator.remove();
                } else {
                    entries.add(value.getDataResponseEntry());
                }

            }
            return entries;
        }
    }

    /**
     * 是否有新的数据
     * @param id
     * @return
     */
    public boolean hasNew(long id) {
        return id < getMaxId() && dataQueue.size() > 0;
    }


}
